<template>
  <div class="common-layout">
    <el-container>
      <el-header> 
        <HeaderPage :avatar="avatar" :nick_name="nick_name" :is_admin="isAdmin"></HeaderPage>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-scrollbar height="500px">
            <div style="display: flex;">
              <el-input  
                v-model="searchInput"  
                @input="onInputChange"  
                clearable  
                placeholder="请输入关键词"  
              ></el-input>  
            </div> 
            <div class="suggestion_group" v-if="suggestions.length!==0">
              <el-button 
                v-for="suggestion in suggestions"
                :key="suggestion.business_id"
                :type="primary"
                link
                v-html="suggestion.highlighted"
                @click="check_words(suggestion.business_id)"
              ></el-button>
            </div>
            <el-collapse>
              <el-collapse-item style="hight:16px" title="高级搜索">
                <div>请选择目标语言类型<el-button round type="default" @click="searchByTags">查询</el-button></div>
                <el-divider/>
                <el-checkbox-group v-model="tag_checked_arr" size="small">
                  <el-checkbox-button 
                      v-for="item in content_tags"
                      :label="item.label"
                      :key="item.key"
                      @change="tag_changed"
                    >
                        {{ item.label }}
                  </el-checkbox-button>
                </el-checkbox-group>
              </el-collapse-item>
            </el-collapse>
            <div class="el-menu-item el-menu--vertical" @click="onReset">查看全部</div>
            <el-menu
                
                class="el-menu-vertical-demo"
                @select="handleSelect"
                >
                <el-menu-item v-for="item in items" 
                  :key="item.key" 
                  :index="item.index"
                  @click="check_first_letter(item.text)">
                 <!-- <router-link style="text-decoration:none;margin-left:10dvw" :to="{name:'WordsBank',params:{param1 :item.index}}"><span>{{item.text}}</span></router-link> -->
                 {{item.text}}
                </el-menu-item>
            </el-menu>
          </el-scrollbar>
        </el-aside>
        <el-main>
           <router-view :key="randomID"></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
 
  <FooterPage></FooterPage>
</template>

<script>
import HeaderPage from '@/components/HeaderPage.vue'
import FooterPage from '@/components/FooterPage.vue'
import config from '../../spoken.config.json'
import { ElNotification } from 'element-plus'
import {JSEncrypt} from 'jsencrypt'

export default {
  name: 'HomePage',
  props: {
    msg: String
  },
  components:{
    HeaderPage,
    FooterPage,
  },

  data(){
    return{
      content_tags:config.CONTENT_TAGS,
      searchInput:'',
      isAdmin:false,
      suggestions:[],
      nick_name:null,
      user_id:null,
      avatar:null,
      tag_checked_arr:[],
      Header:'口语词典',
      randomID:Date.now(),
      // activeIndex:'A',
      items:[
        {key:1,index:'A',text:'A'},
        {key:2,index:'B',text:'B'},
        {key:3,index:'C',text:'C'},
        {key:4,index:'D',text:'D'},
        {key:5,index:'E',text:'E'},
        {key:6,index:'F',text:'F'},

        {key:7,index:'G',text:'G'},
        {key:8,index:'H',text:'H'},
        {key:9,index:'I',text:'I'},
        {key:10,index:'J',text:'J'},
        {key:11,index:'K',text:'K'},
        {key:12,index:'L',text:'L'},

        {key:13,index:'M',text:'M'},
        {key:14,index:'N',text:'N'},
        {key:15,index:'O',text:'O'},
        {key:16,index:'P',text:'P'},
        {key:17,index:'Q',text:'Q'},
        {key:18,index:'R',text:'R'},

        {key:19,index:'S',text:'S'},
        {key:20,index:'T',text:'T'},
        {key:21,index:'U',text:'U'},
        {key:22,index:'V',text:'V'},
        {key:23,index:'W',text:'W'},
        {key:24,index:'X',text:'X'},

        {key:25,index:'Y',text:'Y'},
        {key:26,index:'Z',text:'Z'},
      ],
    }
  },

  created(){
    this.user_profiles();
  },

  watch:{
    
  },

  methods:{
   async onInputChange(newValue) {  
    this.tag_checked_arr=[]  
    // 执行Elastic的联想查询，根据newValue查询相关建议，并更新suggestions数组
     const data={
              method:"es",
              es_query_type:"Mandarin_Key_Word",
              user_id:this.user_id,
              page:this.page,
              page_size:config.PAGE_SIZE,
              keywords:newValue,
            }  
            if(newValue===''){
              this.onReset();
            }else{
              this.suggestions=await this.check_esdata(data);
              console.log('onInputChange返回的suggestions数据：'+JSON.stringify( this.suggestions));
            }
    },  
   
    onReset() {  
      // 恢复默认状态  
      console.log("dictionary页面重置中……")
      this.tag_checked_arr=[]
      this.randomID=Date.now()
      this.$router.push( {name: "Wordsbank", params: { param1: 'all' }} )
    }, 

    tag_changed(){
      console.log(this.tag_checked_arr)
    },

    handleSelect(index,key){
      this.defaultActive=index;
      console.log("handleSelect: "+index+" el-meun-item-key: "+key);
    },

    // 按标签查询
    async searchByTags(){
      try{
        const data={
              method:"es",
              es_query_type:"Tag",
              user_id:this.user_id,
              page:this.page,
              page_size:config.PAGE_SIZE,
              keywords:this.tag_checked_arr,
            }  
            let bids=[]
            const res=await this.check_esdata(data)
            res.forEach(element => {
              bids.push(String(element.business_id))
            });
            console.log("按首字母查询的bid索引："+(JSON.stringify(bids)));
            document.cookie = "conditions="+JSON.stringify(bids)+"; expires=" + new Date().setDate(new Date().getDate() + 7) + "; path=/";
            const cookie_conditions=this.$commonFunctions.get_cookies('conditions');
            console.log("check_first_letter函数内检查cookie_conditaions的值： "+cookie_conditions);
            //this.$router.push({ path: '/', params: { param1: 'all' } });
            this.randomID=Date.now()
            this.$router.push( {name: "Wordsbank", params: { param1: 'all' }} )
    
        this.tag_checked_arr=[]
      }
      catch (err){
        console.log(err)
      }

    },

    // 调查询es
    async check_esdata(data){
      const res=await this.$commonFunctions.check_assets(data);
      if(res.code===20000){
          console.log("check_esdata函数的出参结果："+JSON.stringify(res.data['results']))
          return res.data['results'];
        }else{
          ElNotification({
                        message: '查询ES失败，请联系管理员('+res.code+')',
                        title: "系统消息",
                        type: "warning",
                        duration: 3000,
                    }); 
        }
      },

    // 按首字母查询
    async check_first_letter(letter){
      this.tag_checked_arr=[]
      const data={
              method:"es",
              es_query_type:"First_Letter",
              user_id:this.user_id,
              page:this.page,
              page_size:config.PAGE_SIZE,
              keywords:letter,
            }  
            let bids=[]
            const res=await this.check_esdata(data)
            res.forEach(element => {
              bids.push(String(element.business_id))
            });
            console.log("按首字母查询的bid索引："+(JSON.stringify(bids)));
            document.cookie = "conditions="+JSON.stringify(bids)+"; expires=" + new Date().setDate(new Date().getDate() + 7) + "; path=/";
            const cookie_conditions=this.$commonFunctions.get_cookies('conditions');
            console.log("check_first_letter函数内检查cookie_conditaions的值： "+cookie_conditions);
            //this.$router.push({ path: '/', params: { param1: 'all' } });
            this.randomID=Date.now()
            this.$router.push( {name: "Wordsbank", params: { param1: 'all' }} )
    
    }, 

    // 查询词条
    async check_words(key){
      this.suggestions=[];
      console.log("check_words入参检查："+key)
      document.cookie = "conditions="+JSON.stringify(key)+"; expires=" + new Date().setDate(new Date().getDate() + 7) + "; path=/";
      const cookie_conditions=this.$commonFunctions.get_cookies('conditions');
      console.log("check_words函数内检查cookie_conditaions的值： "+cookie_conditions);
      //this.$router.push({ path: '/', params: { param1: 'all' } });
      this.randomID=Date.now
      this.$router.push( {name: "Wordsbank", params: { param1: 'all' }} )
    },

    //页面初始化
    async user_profiles(){
                //读cookie，获取用户token
                const login_token= this.$commonFunctions.get_cookies('login_token')
                console.log("Dictionary页面初始化数据。login_token："+login_token);
             
                const user_profiles= await this.$commonFunctions.get_user_profiles(login_token);
              
                this.nick_name=user_profiles.name
                this.avatar=user_profiles.avatar
                this.user_id=user_profiles.user_id
                this.isAdmin=user_profiles.is_superuser

                //把昵称和头像信息存到cookie里
                
                console.log("Dictionary页面初始化数据。用户名："+this.nick_name+" 头像地址："+this.avatar+" 管理员标识："+user_profiles.is_superuser);
             },
  },
 
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
router-link{
  text-decoration:none;}

  .suggestion_group{
    border: 1px solid #dcdfe6;
    padding: 10px 5px;
    border-radius: 3px;
    background-color: #f1f1f16b;
  }
  
  .el-menu-item{
    margin: 10px 20px 0px 20px;
    cursor:pointer;
  }
  .el-menu-item:hover{
    color:#4473d2 ;
  }
  .el-menu--vertical{
    padding-left:25% ;
  }
</style>
